import asyncio
import sys
sys.path.append("c:/Users/Windows10/Desktop/MAESS/maess_-flow")

from apps.orchestrator.async_orchestrator_agent import AsyncOrchestratorAgent
from utils.logger import Logger
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import logging

# 配置日志
logger = Logger.get_logger(agent_name="async_orchestrator_service")

# 创建FastAPI应用
app = FastAPI(
    title="Async Orchestrator API",
    description="异步编排服务API",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 全局异步编排器实例
orchestrator_instance = None

@app.on_event("startup")
async def startup_event():
    """服务启动事件"""
    global orchestrator_instance
    try:
        # 初始化异步编排器
        orchestrator_instance = await AsyncOrchestratorAgent().__aenter__()
        logger.success("异步编排器服务启动成功！")
    except Exception as e:
        logger.error(f"异步编排器启动失败: {str(e)}")
        raise

@app.on_event("shutdown")
async def shutdown_event():
    """服务关闭事件"""
    global orchestrator_instance
    if orchestrator_instance:
        try:
            await AsyncOrchestratorAgent().__aexit__(None, None, None)
            logger.success("异步编排器服务关闭成功！")
        except Exception as e:
            logger.error(f"异步编排器关闭失败: {str(e)}")

@app.get("/")
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "service": "async_orchestrator",
        "timestamp": asyncio.get_event_loop().time()
    }

if __name__ == "__main__":
    # 启动FastAPI服务
    uvicorn.run(
        "start_async_orchestrator:app",
        host="0.0.0.0",
        port=8002,
        reload=True,
        log_level="info"
    )
